package eerbaar.v2.effects.internal;

import java.awt.Graphics2D;
import java.util.Date;

import eerbaar.game.IGame;
import eerbaar.message.lib.DisplayMessageMsg;
import eerbaar.message.lib.NotifyPetMove;
import eerbaar.shared.message.IMessageReader;
import eerbaar.shared.message.Message;
import eerbaar.shared.message.MsgHelper;
import eerbaar.v2.app.GameHelper;
import eerbaar.v2.effects.Effect;

public class PopupText implements Effect {

    private final String text;
    private boolean expired;
    private final long startTime;
    private final long expireTime;
    private final int MAX_AGE = 7 * 1000;

    private final IMessageReader moveReader = new IMessageReader() {

        @Override
        public boolean read(Message msg) {
            term();
            return false;
        }
    };

    private final IMessageReader displayReader = new IMessageReader() {

        @Override
        public boolean read(Message msg) {
            term();
            return false;
        }
    };

    public PopupText(String text) {
        this.text = text;
        MsgHelper.registerReader(NotifyPetMove.class, this.moveReader);
        MsgHelper.registerReader(DisplayMessageMsg.class, this.displayReader);
        this.startTime = new Date().getTime();
        this.expireTime = (this.startTime + this.MAX_AGE);
    }

    @Override
    public void display(int time, Graphics2D canvas) {

        IGame game = GameHelper.getGame();
        if (game == null) {
            return;
        }

        PopupRect rect = new PopupRect(game, this.text, canvas);
        rect.display(canvas);
    }

    @Override
    public boolean isExpired(int time) {

        long now = new Date().getTime();
        if (now > this.expireTime) {
            this.expired = true;
        }

        return this.expired;
    }

    @Override
    public void setExpired(boolean expired) {
        //
    }

    private void term() {

        this.expired = true;
        MsgHelper.unregisterReader(NotifyPetMove.class, this.moveReader);
        MsgHelper.unregisterReader(DisplayMessageMsg.class, this.displayReader);
    }

}
